package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.heima.client.ArticleFeign;
import com.heima.common.aliyun.GreenImageUploadScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JsonUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import com.heima.wemedia.entity.WmNews;
import com.heima.wemedia.service.WmNewAutidService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@Slf4j
public class WmNewAutidServiceImpl implements WmNewAutidService {

    @Autowired
    private ArticleFeign articleFeign;

    @Override
    @Async
    public void auditWmNew(WmNews wmNews) {
        //判断文章状态为1待审核
        if (wmNews == null || wmNews.getStatus() != 1) {
            log.error("文章状态不对不是审核状态");
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = wmNews.getId();
        //@获取文章的文字和图片
        Map<String, Object> map = getTestAndImage(wmNews);
        //@调用第三方接口审核文字
        String text = map.get("text").toString();
        List<byte[]> list = (List<byte[]>) map.get("image");
        boolean b = checkTest(text, id);
        if (b != true) {
            log.error("文本审核不通过");
            return;
        }
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        boolean b1 = checkImage(list,id);
        if (b != true) {
            log.error("图片审核不通过");
            return;
        }
        //@调用第三方接口审核图片
        //@进行铭感词的审核
        //@获取图片的文字惊醒铭感词的审核
        //修改文章审核状态 8审核通过
        updateNewStatus(id, 8, null, null);
        //判断发布时间
        Date publishTime = wmNews.getPublishTime();
        if (publishTime != null && System.currentTimeMillis() < publishTime.getTime()) {
            log.error("没有到发布时间");
            return;
        }

        //远程调用article服务发布文章
        WmNewsResultDTO dto = BeanHelper.copyProperties(wmNews, WmNewsResultDTO.class);
        try {
            Long articleId = articleFeign.save(dto);
            updateNewStatus(id, 9, null, articleId);
        } catch (Exception e) {
            log.error("");
            e.printStackTrace();
        }


        //修改文章审核状态 9发布文章


    }

    @Autowired
    private GreenImageUploadScan scan;
    private boolean checkImage(List<byte[]> list, Integer id) {
        try {
            Map<String, String> map = scan.imageScan(list);
            String suggestion = map.get("suggestion");
            String label = map.get("label");
            if ("pass".equals(suggestion)){
                return true;
            }else if("review".equals(suggestion)){
              updateNewStatus(id, 3, label, null);
                return false;
            }else
            {
                updateNewStatus(id, 2, label, null);
                return false;
            }
        } catch (Exception e) {
            log.error("阿里云图片检测异常");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
    }

    @Autowired
    private GreenTextScan greenTextScan;

    private boolean checkTest(String text, Integer id) {
        try {
            Map<String, String> map = greenTextScan.greenTextScan(text);
            String suggestion = map.get("suggestion");
            String reason = map.get("reason");
            if (suggestion.equals("pass")) {
                return true;
            } else if (suggestion.equals("review")) {
                this.updateNewStatus(id, 3, reason, null);
                return false;
            } else {
                this.updateNewStatus(id, 2, reason, null);
                return false;
            }
        } catch (Exception e) {
            log.error("阿里云文本检查异常");
            e.printStackTrace();
            return false;
        }
    }

    @Autowired
    private MinioService minioService;

    private Map<String, Object> getTestAndImage(WmNews wmNews) {
        Map<String, Object> map = new HashMap<>();
        List<byte[]> image = new ArrayList();
        StringBuilder str = new StringBuilder();
        str.append(wmNews.getTitle()).append(wmNews.getContent());
        String content = wmNews.getContent();
        List<Map<String, Object>> list = JsonUtils.nativeRead(content, new TypeReference<List<Map<String, Object>>>() {
        });
        for (Map<String, Object> stringObjectMap : list) {

            String type = stringObjectMap.get("type").toString();
            String value = stringObjectMap.get("value").toString();
            if ("text".equals(type)) {
                str.append(",").append(value);
            } else {
                byte[] bytes = minioService.downLoadFile(value);
                image.add(bytes);
            }
        }
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)) {
            String[] split = wmNews.getImages().split(",");
            for (String s : split) {

                byte[] bytes = minioService.downLoadFile(s);
                image.add(bytes);
            }
        }
        map.put("image", str.toString());
        map.put("test", image);

        return null;
    }

    @Autowired
    @Lazy
    private WmNewsService service;

    private void updateNewStatus(Integer id, int status, String reason, Long articleid) {

        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        wmNews.setReason(reason);
        wmNews.setStatus(status);
        wmNews.setArticleId(articleid);
        service.updateById(wmNews);
    }
}
